<template>
  <div class="app-container">
    <!-- 仓库信息 -->
    <el-card shadow="never" class="mb20">
      <div slot="header">
        <span>仓库信息</span>
        <el-button
          style="float: right; margin-left: 10px; padding: 3px 0"
          type="text"
          icon="el-icon-back"
          @click="handleBack"
        >返回仓库列表</el-button>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-refresh"
          @click="handleSwitchWarehouse"
        >切换仓库</el-button>
      </div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="仓库名称">{{ warehouseInfo.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="仓库编码">{{ warehouseInfo.warehouseCode }}</el-descriptions-item>
        <el-descriptions-item label="仓库地址">{{ warehouseInfo.warehouseAddress }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ warehouseInfo.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ warehouseInfo.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="仓库状态">
          {{ 
            (statusOptions.find(item => item.dictValue === String(warehouseInfo.warehouseStatus)) || {}).dictLabel 
            || warehouseInfo.warehouseStatus 
          }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="库区名称" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入库区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库区类型" prop="areaType">
        <el-select
          v-model="queryParams.areaType"
          placeholder="请选择库区类型"
          clearable
        >
          <el-option
            v-for="dict in areaTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['wms:area:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:area:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:area:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['wms:area:export']"
        >导出</el-button>
      </el-col>

    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="areaList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库区编号" align="center" prop="areaCode" />
      <el-table-column label="库区名称" align="center" prop="areaName" />
      <el-table-column label="库区类型" align="center" prop="areaType">
        <template slot-scope="scope">
          <span>{{ 
            (areaTypeOptions.find(item => item.dictValue === String(scope.row.areaType)) || {}).dictLabel 
            || scope.row.areaType 
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库区状态" align="center" prop="areaStatus">
        <template slot-scope="scope">
          <span>{{ 
            (statusOptions.find(item => item.dictValue === String(scope.row.areaStatus)) || {}).dictLabel 
            || scope.row.areaStatus 
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:area:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:area:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-location-information"
            @click="handleLocation(scope.row)"
            v-hasPermi="['wms:location:list']"
          >库位管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库区对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库区名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入库区名称" />
        </el-form-item>
        <el-form-item label="库区编码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入库区编码" />
        </el-form-item>
        <el-form-item label="库区类型" prop="areaType">
          <el-select v-model="form.areaType" placeholder="请选择库区类型">
            <el-option
              v-for="dict in areaTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库区状态" prop="areaStatus">
          <el-select v-model="form.areaStatus" placeholder="请选择库区状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 仓库选择对话框 -->
    <el-dialog
      title="请选择仓库"
      :visible.sync="warehouseSelectVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form>
        <el-form-item label="仓库" label-width="80px">
          <el-select 
            v-model="selectedWarehouseId" 
            placeholder="请选择仓库" 
            style="width: 100%"
            @change="confirmWarehouseSelection"
            @visible-change="autoConfirmIfSingle"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName + ' (' + item.warehouseCode + ')'"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listArea, getArea, addArea, updateArea, deleteArea } from "@/api/wms";
import { getWarehouse, listWarehouse } from "@/api/wms";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Area",
  data() {
    return {
      // 仓库和库区选择对话框
      warehouseAreaSelectVisible: false,
      selectedWarehouseId: '',
      selectedAreaId: '',
      warehouseList: [],
      areaList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 库区表格数据
      areaList: [],
      // 仓库信息
      warehouseInfo: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 仓库选择对话框
      warehouseSelectVisible: false,
      // 仓库列表
      warehouseList: [],
      // 选中的仓库ID
      selectedWarehouseId: "",
      // 状态数据字典
      statusOptions: [],
      // 库区类型数据字典
      areaTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: undefined,
        areaName: undefined,
        areaType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: "库区名称不能为空", trigger: "blur" }
        ],
        areaCode: [
          { required: true, message: "库区编码不能为空", trigger: "blur" }
        ],
        areaType: [
          { required: true, message: "库区类型不能为空", trigger: "change" }
        ],
        areaStatus: [
          { required: true, message: "库区状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.initPageData();
    this.getDicts();
    this.checkNeedSelection();
  },
  watch: {
    // 监听路由参数变化，当仓库ID变化时重新加载数据
    '$route.query.warehouseId': {
      handler(newWarehouseId) {
        if (newWarehouseId && newWarehouseId !== this.queryParams.warehouseId) {
          this.initPageData();
        }
      },
      immediate: false
    }
  },
  methods: {
    // 初始化页面数据
    initPageData() {
      const warehouseId = this.$route.query.warehouseId;
      if (warehouseId) {
        // 从仓库管理页面跳转过来，有仓库ID参数
        this.queryParams.warehouseId = warehouseId;
        this.form.warehouseId = warehouseId;
        this.getWarehouseInfo(warehouseId);
        this.getList();
      } else {
        // 从菜单直接进入，弹出仓库选择对话框
        this.selectWarehouse();
      }
    },
    // 选择仓库
    selectWarehouse() {
      // 获取仓库列表
      this.loading = true;
      listWarehouse().then(response => {
        const warehouses = response.rows || [];
        if (warehouses.length === 0) {
          this.$modal.msgError('没有可用的仓库');
          this.handleBack();
          return;
        }
        
        // 保存仓库列表
        this.warehouseList = warehouses;
        this.selectedWarehouseId = '';
        
        // 显示仓库选择对话框
        this.warehouseSelectVisible = true;
      }).catch(error => {
        this.$modal.msgError('获取仓库列表失败: ' + error.message);
        this.handleBack();
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 确认仓库选择
    confirmWarehouseSelection(warehouseId) {
      if (!warehouseId) {
        return;
      }
      
      // 设置选中的仓库ID
      this.selectedWarehouseId = warehouseId;
      this.queryParams.warehouseId = warehouseId;
      this.form.warehouseId = warehouseId;
      
      // 关闭对话框
      this.warehouseSelectVisible = false;
      
      // 加载仓库信息和库区列表
      this.getWarehouseInfo(warehouseId);
      this.getList();
      this.getDicts();
    },

    // 如果只有一个仓库则自动确认
    autoConfirmIfSingle(visible) {
      if (!visible && this.warehouseList.length === 1) {
        this.confirmWarehouseSelection(this.warehouseList[0].warehouseId);
      }
    },
    
    /** 查询库区列表 */
    getList() {
      this.loading = true;
      listArea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取仓库信息
    getWarehouseInfo(warehouseId) {
      getWarehouse(warehouseId).then(response => {
        this.warehouseInfo = response.data;
      });
    },
    // 获取数据字典
    getDicts() {
      getDicts("wms_area_status").then(response => {
        this.statusOptions = response.data;
      }).catch(() => {
        // 回退到系统默认状态字典
        getDicts("sys_normal_disable").then(response => {
          this.statusOptions = response.data;
        });
      });
      
      getDicts("wms_area_type").then(response => {
        this.areaTypeOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        areaId: undefined,
        warehouseId: this.queryParams.warehouseId,
        areaName: undefined,
        areaCode: undefined,
        areaType: undefined,
        areaStatus: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.areaId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库区";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const areaId = row.areaId || this.ids;
      getArea(areaId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库区";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.areaId != null) {
            updateArea(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArea(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const areaIds = row.areaId || this.ids;
      this.$modal.confirm('是否确认删除库区编号为"' + areaIds + '"的数据项？').then(function() {
        return deleteArea(areaIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 库位管理按钮操作 */
    handleLocation(row) {
      const areaId = row.areaId;
      this.$router.push({ 
        path: "/wms/location/index",
        query: { 
          warehouseId: this.queryParams.warehouseId, 
          areaId: areaId 
        } 
      });
    },
    /** 返回仓库列表 */
    handleBack() {
      this.$router.push("/wms/warehouse");
    },
    
    // 仓库选择变化时加载对应库区
    handleWarehouseChange(warehouseId) {
      if (!warehouseId) {
        this.areaList = [];
        this.selectedAreaId = '';
        return;
      }
      
      this.loading = true;
      listArea({ warehouseId }).then(response => {
        this.areaList = response.rows || [];
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 确认选择仓库和库区
    confirmSelection() {
      if (!this.selectedWarehouseId || !this.selectedAreaId) {
        this.$message.warning('请选择仓库和库区');
        return;
      }
      
      const selectedWarehouse = this.warehouseList.find(w => w.warehouseId === this.selectedWarehouseId);
      const selectedArea = this.areaList.find(a => a.areaId === this.selectedAreaId);
      
      this.queryParams.warehouseId = this.selectedWarehouseId;
      this.warehouseInfo = selectedWarehouse;
      this.getList();
      this.warehouseAreaSelectVisible = false;
    },
    
    // 检查是否需要显示选择对话框
    checkNeedSelection() {
      if (!this.$route.query.warehouseId || !this.$route.query.areaId) {
        this.warehouseAreaSelectVisible = true;
        this.loadWarehouses();
      }
    },
    
    // 加载仓库列表
    loadWarehouses() {
      this.loading = true;
      listWarehouse().then(response => {
        this.warehouseList = response.rows || [];
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 切换仓库 */
    handleSwitchWarehouse() {
      // 调用选择仓库方法，复用已有的仓库选择对话框
      this.selectWarehouse();
    },
    /** 导出按钮操作 */
    handleExport() {
      // 确保仓库ID被正确传递
      if (!this.queryParams.warehouseId) {
        this.$modal.msgError('请先选择仓库');
        return;
      }
      
      // 使用简化的导出方式，与仓库管理页面保持一致
      this.download(
        'wms/area/export', 
        {
          ...this.queryParams
        }, 
        `area_${this.warehouseInfo.warehouseName || '未知仓库'}_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>